<?php
declare (strict_types = 1);

namespace app\middleware;

use app\console\model\Config;
use app\model\Member;
use app\model\MemberIntegral;
use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenBlacklistException;
use thans\jwt\exception\TokenExpiredException;
use thans\jwt\exception\TokenInvalidException;
use thans\jwt\facade\JWTAuth;
use think\facade\Log;

class RequestData
{
    /**
     * 处理请求参数
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        try {

            $payload = JWTAuth::auth();
//            var_dump($payload);
            Log::record($payload);
            Log::record(JWTAuth::token()->get());

            $request->member_id = $payload['member_id']->getValue();
            $black = Config::where('varname','web_black')->value('varvalue');
            $black_arg = textAreaArray($black);
            $mobile = Member::where('mobile','in',$black_arg)->column('id');

            if(in_array($request->member_id,$mobile)){
                abort(response('out'));
            }
        }catch (TokenInvalidException $e){
            return abort(0,'token非法');
        }catch (TokenExpiredException $e){
            return abort(0,'token过期');
        }catch (TokenBlacklistException $e){
            return abort(0,'请重新获取登录凭据');
        }catch (JWTException  $e) {
            //$e->getCode(),$e->getMessage()
            //return abort(json(['code'=>0,'msg'=>$e->getMessage()]));
        }

        Log::record($request->url(true),'info');
        $param = $request->param();
        $param['member_id'] = $request->member_id;
        if(!empty($param)){
            Log::write(var_export($param,true));
        }
        $request->withMiddleware($param);
        $request->data = $param;
        $request->param = $param;
//        $request->start_time = microtime(true);
        return $next($request);
    }

}
